﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class NewsInfoController : BaseApiController
    {
        public IEnumerable<NewsInfo> GetNewsList()
        {
            var list = from n in db.NewsInfo orderby n.NewsPostTime descending select n;
            if (list != null && list.Count() > 0) {
                foreach (var item in list)
                {
                    int type = item.NewsType;
                    item.NewsTypeName = Enum.GetName(typeof(Enums.NewsType), type);
                    item.DisplayTime = item.NewsPostTime.ToString("yyyy-MM-dd hh:mm:ss");
                }
            }
            return list;
        }

        /// <summary>
        /// 分页读取列表
        /// </summary>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        public List<NewsInfo> GetSpiltPageList(int pageIndex, int pageSize) {
            List<NewsInfo> spiltPageList=null;
            var list = from n in db.NewsInfo orderby n.NewsPostTime descending select n;
            int count = list.Count();
            if (count > 0 && pageIndex >= 1 && pageSize >= 0)
            {
                //分页数据  
                spiltPageList = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                foreach (var item in list)
                {
                    int type = item.NewsType;
                    item.NewsTypeName = Enum.GetName(typeof(Enums.NewsType), type);
                    item.DisplayTime = item.NewsPostTime.ToString("yyyy-MM-dd hh:mm:ss");
                }
            }
            return spiltPageList;
        }

        /// <summary>
        /// 读取前3条数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<NewsInfo> GetTopNews() {
            var list = from n in db.NewsInfo orderby n.NewsPostTime descending select n;
            foreach (var item in list)
            {
                int type = item.NewsType;
                item.NewsTypeName = Enum.GetName(typeof(Enums.NewsType), type);
                item.DisplayTime = item.NewsPostTime.ToString("yyyy-MM-dd hh:mm:ss");
            }
            return list.Take(3);
        }
    }
}
